<?php
/**
 * 内容标签类
 * @Author hugo
 * @Email webmaster@jushare.com
 */
namespace Common\TagLib;
use Think\Template\TagLib;

class Content extends TagLib{
    // 标签定义
    protected $tags   =  array(
        // 标签定义： attr 属性列表 close 是否闭合（0 或者1 默认1） alias 标签别名 level 嵌套层次
        'item' => array('attr'=>'table,condition,fields,name', 'close' => 0),

    );

    public function _item($tag,$content) {
        $parseStr = <<<str
<?php
    \$__ITEMDATA__ = D('[table]')->where([condition])->field('[fields]')->find();
    [__TODO__]
?>
str;

        $name = isset($tag['name']) ? $tag['name'] : '';
        $table = empty($tag['table']) ? ucfirst(CONTROLLER_NAME) : ucfirst($tag['table']);
        $fields = isset($tag['fields']) ? $tag['fields'] : '*';
        $condition = isset($tag['condition']) ? $tag['condition'] : '';
        $parseStr = str_replace(array('[table]', '[condition]', '[fields]'), array($table, $condition, $fields), $parseStr);
        if(empty($name)){
            $parseStr = str_replace('[__TODO__]', 'extract($__ITEMDATA__);', $parseStr);
        }else{
            $parseStr = str_replace('[__TODO__]', '', $parseStr);
            $parseStr = str_replace('__ITEMDATA__', $name, $parseStr);
        }
        return $parseStr;
    }

    /**
     * 函数集
     */
    function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] = & $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] = & $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent = & $refer[$parentId];
                        $parent[$child][] = & $list[$key];
                    }
                }
            }
        }
        return $tree;
    }
}